package com.ruoyi.api.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 1、创建SocketChannel通道对象，并绑定服务器IP和端口信息进行连接请求

 2、直接通过缓冲区向服务器发送数据

 3、直接尝试从通道中读取数据发到缓冲区
 */
public class NioClient {

    private SocketChannel channel;

    public static void main(String[] args) throws Exception {
        NioClient client = new NioClient();
        client.initClient();
        client.sendMsg("Hello NIO Server");
        client.receiveMsg();
    }

    /** 初始化客户端*/
    private void initClient() throws Exception{
        /** 1.创建客户端通道,并绑定服务器IP和端口号 */
        channel = SocketChannel.open(new InetSocketAddress("localhost", 8000));
    }

    /** 发送数据到服务端*/
    private void sendMsg(String msg) throws IOException {
        byte[] bytes = msg.getBytes();
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        /** 向通道发送数据 */
        channel.write(buffer);
        buffer.clear();
    }

    /** 从服务器接收数据*/
    private void receiveMsg() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(2048);
        channel.read(buffer);
        System.out.println(new String(buffer.array()));
        channel.close();
    }
}
